﻿<%@ WebHandler Language="C#" Class="ZSDispatchReport" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Net;
using ReportBusiness;

/**
 * Description: 装配试车厂派报工查询报表
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2022.11.24
 **/

public class ZSDispatchReport : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getDetail":
                        r = getDetail(jObject);//查询明细
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    //查询方法
    Result getData(JObject jObject)
    {
        string sql = @"
SELECT ep.mfgordername,ep.machineno attributevalue,
       m.engineproductname productdesc,
       mfg.factorystardate,
       m.productfamilyname,
       ep.containerno,
       wfs.workflowstepname,
       pb.productname bujian,
       pp.description bujiandesc,
       csd.containerid,
       ep.plannedstartdate,
       ep.plannedfinishdate
FROM enginepartplan ep
LEFT JOIN mfg_engine_data m ON m.mfgorderid = ep.mfgorderid
LEFT JOIN mfgorder mfg ON mfg.mfgorderid = ep.mfgorderid
LEFT JOIN workflowstep wfs ON wfs.workflowstepid = ep.workflowstepid--大阶段
LEFT JOIN product pp ON pp.productid = ep.productid--部件件号
LEFT JOIN productbase pb ON pb.productbaseid = pp.productbaseid
INNER JOIN containersteprecord csd ON csd.containerid = NVL(ep.containerid,ep.enginecontainerid)
LEFT JOIN team t ON csd.teamid=t.teamid
LEFT JOIN Factory f ON f.factoryid = csd.factoryid
WHERE ep.containerno IS NOT NULL AND f.factoryname = '{0}' ";
        sql = string.Format(sql, jObject["factoryname"].ToString());
        //派工时间
        if (jObject["dispatchdate"] != null && jObject["dispatchdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["dispatchdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND csd.dispatchdate >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss')", arr[0].ToString());
                sql += string.Format(" AND csd.dispatchdate <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss')", arr[1].ToString());
            }
        }

        //报工时间
        if (jObject["reportdate"] != null && jObject["reportdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["reportdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND csd.reportdate >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss')", arr[0].ToString());
                sql += string.Format(" AND csd.reportdate <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss')", arr[1].ToString());
            }
        }

        //检验时间
        if (jObject["checkdate"] != null && jObject["checkdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["checkdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND csd.checkdate >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss')", arr[0].ToString());
                sql += string.Format(" AND csd.checkdate <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss')", arr[1].ToString());
            }
        }

        //订单号
        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND mfg.mfgordername = '{0}'", jObject["mfgordername"].ToString());
        }

        //发动机号
        if (jObject["engineno"] != null && jObject["engineno"].ToString() != "")
        {
            sql += string.Format(" AND ep.machineno = '{0}'", jObject["engineno"].ToString());
        }

        //机型
        if (jObject["productfamilyname"] != null && jObject["productfamilyname"].ToString() != "")
        {
            sql += string.Format(" AND m.productfamilyname = '{0}'", jObject["productfamilyname"].ToString());
        }

        // 部件号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND pb.productname = '{0}'", jObject["productname"].ToString());
        }

        //组
        if (jObject["teamname"] != null && jObject["teamname"].ToString() != "")
        {
            sql += string.Format(" AND t.teamname LIKE '%{0}%'", jObject["teamname"].ToString());
        }

        //任务单号
        if (jObject["containerno"] != null && jObject["containerno"].ToString() != "")
        {
            sql += string.Format(" AND ep.containerno = '{0}'", jObject["containerno"].ToString());
        }

        //阶段
        if (jObject["workflowstepname"] != null && jObject["workflowstepname"].ToString() != "")
        {
            sql += string.Format(" AND wfs.workflowstepname LIKE '%{0}%'", jObject["workflowstepname"].ToString());
        }

        sql += @"
GROUP BY ep.mfgordername,ep.machineno,m.engineproductname,mfg.factorystardate,m.productfamilyname,ep.containerno,wfs.workflowstepname,
         pb.productname,pp.description,csd.containerid,ep.plannedstartdate,ep.plannedfinishdate";

        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //查询明细
    Result getDetail(JObject jObject)
    {
        string sql = @" 
SELECT csd.plannedstartdate,csd.plannedfinishdate,wfs.workflowstepname,si.Description,t.teamname,getonlyfullname(csd.employeeid) dispatcher,
       csdd.toPerson,csd.createdate dispatchdate,getonlyfullname(csw.workerid) worker,csw.createdate workdate,
       getonlyfullname(cci.checkerid) checker,cci.createdate checkdate,csw.reasondesc 
FROM containerstepdispatch csd
LEFT JOIN containerstepworkreport csw ON csd.containerstepdispatchid=csw.containerstepdispatchid AND csw.isuse = 0
LEFT JOIN containercheckinfo cci ON cci.containerstepworkreportid=csw.containerstepworkreportid AND cci.isuse = 0
LEFT JOIN workflowstep wfs ON csd.Workflowstepid=wfs.workflowstepid
LEFT JOIN stepinfo SI ON si.Stepinfoid=csd.stepinfoid
LEFT JOIN team t ON csd.teamid=t.teamid
LEFT JOIN 
(
    SELECT csdd.containerstepdispatchid,listagg(e.fullname,'、') WITHIN GROUP (ORDER BY csdd.containerstepdispatchid) toPerson
    FROM containerstepdispatchdetail_zs csdd
    LEFT JOIN employee e ON e.employeeid = csdd.workerid
    GROUP BY csdd.containerstepdispatchid
) csdd ON csd.containerstepdispatchid =  csdd.containerstepdispatchid --若派工给多个人，按顿号（、）合并为一条记录 
WHERE csd.isuse = 0 AND csd.containerid='{0}'";

        sql = string.Format(sql, jObject["containerid"].ToString());

        //派工时间
        if (jObject["dispatchdate"] != null && jObject["dispatchdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["dispatchdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND csd.createdate >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss')", arr[0].ToString());
                sql += string.Format(" AND csd.createdate <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss')", arr[1].ToString());
            }
        }

        //报工时间
        if (jObject["reportdate"] != null && jObject["reportdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["reportdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND csw.createdate >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss')", arr[0].ToString());
                sql += string.Format(" AND csw.createdate <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss')", arr[1].ToString());
            }
        }

        //检验时间
        if (jObject["checkdate"] != null && jObject["checkdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["checkdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND cci.createdate >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss')", arr[0].ToString());
                sql += string.Format(" AND cci.createdate <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss')", arr[1].ToString());
            }
        }

        //组
        if (jObject["teamname"] != null && jObject["teamname"].ToString() != "")
        {
            sql += string.Format(" AND t.teamname ='{0}'", jObject["teamname"].ToString());
        }

        sql += "ORDER BY wfs.workflowstepname";

        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }
}